/*
 * @Author: luoqi
 * @Date: 2022-03-27 15:09:41
 * @LastEditors: luoqi
 * @LastEditTime: 2022-04-27 16:27:48
 * @Description: 
 */
import React, { useState ,useEffect} from 'react';
import { Form, Input, Button, Select, Space, Card, Table, Tag ,Popconfirm, message} from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';

import {connect} from 'react-redux'
import {addTab,changeActive} from '../../store/tabAction'
import tabs from '../tabs'

import axios from '../../utils/axios'
import qs from 'qs'

import PubSub from 'pubsub-js'
const { Option } = Select;


 function Experience(props) {
  const {departmentTree,partTree} = props.types;
  let [pag, setPag] = useState({ defaultCurrent: 1,  pageSize: 5 ,current:1,showTotal:total => `共 ${total} 条`,onChange:changePage})
  let [form]=Form.useForm()
  let [data, setData] = useState()
  //用于触发重新渲染页面
  let [num, setNum] = useState(0)
  //搜索或全部
  let [isAll,setIsAll]=useState(true)
  //所有一级分类
  let typeArr = props.types;
  //页数更改时
  function changePage(page, pageSize) {
    console.log(page, pageSize);
    setPag({ ...pag, current: page, pageSize })
  }

  //页面加载完毕调接口，页数更改时调接口
  useEffect(() => {

    if(isAll){
      axios({
      url: '/experience/selectByType',
      method: 'get',
      params: {
        page: pag.current,
        size: pag.pageSize,
      }
    }).then(res => {
      console.log(res);
      if (res.code === '200') {
        setIsAll(true)
        //给每一个加key
        setData(res.data.map(item => ({ ...item, key: item.id })))
        setPag({ ...pag, total: res.count })
        if (num == 1) {
          setNum(0)
        }

      }
    })
    }else{
      form.submit()
    }
      //订阅
   let info=PubSub.subscribe('setNumExperience',(_,data)=>{
    setNum(data)
    //  console.log(data);
    })
    return () => {
      PubSub.unsubscribe(info)
    };
  }, [pag.current, num,isAll])

//搜索
  const onFinish = (values) => {
    console.log('Success:', values);
    axios({
      url: '/experience/selectByType',
      method: 'get',
      params: {
        page: pag.current,
        size: pag.pageSize,
        title:values.title,
        tag:values.tag,
        status:values.status,
        author:values.author
      }
    }).then(res => {
      console.log(res);
      if (res.code === '200') {
        setIsAll(false)
        //给每一个加key
        setData(res.data.map(item => ({ ...item, key: item.id })))
        setPag({ ...pag, total: res.count })
          setNum(2)
      }else if(res.code=='5012'){
        //提示
        message.success('没有数据');
    }else if(res.code=='500'){
      //提示
      message.warning('查询失败');
    }
    })
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  }
  //添加知识
  function addKnowledeg(str){
     //点击的选项
     let key=str
     //如果标签不存在就添加一个
     if (!props.tabs.panes.find(i => i.key === key)) {
       console.log(tabs[key]);
       let tab=tabs[key]
       //添加到panes
       props.addTab(tab)
     }else{
       console.log('已经存在');
     }
     props.changeActive(key)
  }
   //删除分类
   function confirm(obj) {
    console.log(obj);
    axios({
      url: '/experience/delete',
      method: 'post',
      data: qs.stringify({ ids: obj.id})
    }).then(res => {
      console.log(res);
      if (res.code == '200') {
        message.success('删除成功');
        console.log(num);
        let num1=num+1
        setNum(num1)
      }
    })
  }
  
  function cancel(e) {
    console.log(e);
    message.error('Click on No');
  }
    //修改知识
    function publishDisease(obj){
      //发布
      PubSub.publish('modifyexp',obj)
      addKnowledeg('modifyexp')
    }
  const columns = [
    {
      title: '经验标题',
      dataIndex: 'title',
      key: 'title',
      width:'250px'
    },
    {
      title: '标签',
      dataIndex: 'tag',
      key: 'tag',

    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '是否发布',
      dataIndex: 'status',
      key: 'status',
      render:text=>(text==1?'已发布':'草稿')
    },
    
    {
      title: '浏览量',
      dataIndex: 'viewNum',
      key: 'viewNum',
    },
    
    {
      title: '收藏量',
      dataIndex: 'collectionNum',
      key: 'collectionNum',
    },
    
    {
      title: '经验状态',
      dataIndex: 'status',
      key: 'status',
      render:text=>(text?'可用':'不可用')
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Button type="primary" ghost onClick={()=>{publishDisease(record);setTimeout(()=>{
            publishDisease(record)
          },1000) }}>修改</Button>
          <Popconfirm
            title="确定要删除该疾病吗?"
            onConfirm={()=>confirm(record)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary" ghost>删除</Button>
          </Popconfirm>
          
        </Space>
      ),
    },
  ];
  return (
    <div>
      <Form
        name="basic"
        form={form}
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        initialValues={{
          status: 1,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Space>
          <Form.Item
            label="经验标题"
            name="title"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="经验标签"
            name="tag"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="经验作者"
            name="author"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="是否发布"
            name="status"
          >
            <Select  style={{ width: 120 }}>
              <Option value={1}>已发布</Option>
              <Option value={0}>草稿</Option>
            </Select>
          </Form.Item>
          <Form.Item
          >
            <Button type="primary" htmlType='submit' icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>
          <Form.Item
          >
           <Button type="success" icon={<PlusOutlined />} onClick={()=>addKnowledeg('addexp')} >
        添加
      </Button>
          </Form.Item>
        </Space>
      </Form>
      <Table columns={columns} dataSource={data} pagination={pag} />
    </div>
  );
}
export default connect(
  state=>({tabs:state.tabs,types:state.types}),{addTab,changeActive}
)(Experience);
